import 'dart:convert';

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 偏好设置工具类
class PrefUtils {
  static final PrefUtils _instance = PrefUtils._internal();

  // 常量键值
  static const String kThemeData = "themeData";
  static const String kStaffInfo = "staffInfo";
  static const String kUnsubscribe = 'kUnsubscribe';
  static const String kToken = "token";
  static const String kPhoneNumber = "phoneNumber";
  static const String kSaleTradeHistory = "kSaleTradeHistory";

  SharedPreferences? _sharedPreferences;

  // 私有构造函数，防止外部实例化
  PrefUtils._internal();

  // PrefUtils 单例
  factory PrefUtils() {
    return _instance;
  }

  static PrefUtils get instance => _instance;

  /// 获取 SharedPreferences 实例
  Future<SharedPreferences> get sharedPreferences async {
    _sharedPreferences ??= await SharedPreferences.getInstance();
    return _sharedPreferences!;
  }

  /// 初始化方法
  Future<void> init() async {
    await sharedPreferences;
  }

  /// 清除所有偏好设置数据
  Future<bool> clearAllPreferences() async {
    final prefs = await sharedPreferences;
    return await prefs.clear();
  }

  /// 设置主题数据
  Future<bool> setThemeData(String value) async {
    final prefs = await sharedPreferences;
    return await prefs.setString(kThemeData, value);
  }

  /// 获取主题数据
  Future<String> getThemeData() async {
    final prefs = await sharedPreferences;
    return prefs.getString(kThemeData) ?? 'primary';
  }

  /// 保存token信息
  Future<bool> setToken(String token) async {
    final prefs = await sharedPreferences;
    return await prefs.setString(kToken, token);
  }

  /// 删除token信息
  Future<bool> removeToken() async {
    final prefs = await sharedPreferences;
    return await prefs.remove(kToken);
  }

  /// 获取token信息
  Future<String> getToken() async {
    final prefs = await sharedPreferences;
    return prefs.getString(kToken) ?? '';
  }

  /// 同步方式获取token（可能为null）
  String? getTokenSync() {
    return _sharedPreferences?.getString(kToken);
  }

  /// 保存手机号码
  Future<bool> setPhoneNumber(String phoneNumber) async {
    final prefs = await sharedPreferences;
    return await prefs.setString(kPhoneNumber, phoneNumber);
  }

  /// 获取手机号码
  Future<String> getPhoneNumber() async {
    final prefs = await sharedPreferences;
    return prefs.getString(kPhoneNumber) ?? '';
  }

  // 订单搜索历史
  PrefStringListData? _saleTradeHistory;

  PrefStringListData get saleTradeHistory {
    return _saleTradeHistory ??=
        PrefStringListData(_sharedPreferences, kSaleTradeHistory);
  }

  // 注销账户列表
  PrefStringListData? _unsubscribeList;

  PrefStringListData get unsubscribeList {
    return _unsubscribeList ??=
        PrefStringListData(_sharedPreferences, kUnsubscribe);
  }
}

/// 通用偏好数据抽象类
abstract class PrefData<T> {
  SharedPreferences? sharedPreferences;
  String key;

  PrefData(this.sharedPreferences, this.key);

  final Rx<T?> _value = Rx<T?>(null);

  /// 保存数据
  void save(T? newValue) {
    _value.value = newValue;
    try {
      saveToLocal();
    } catch (e) {
      // 处理保存错误
    }
  }

  /// 保存到本地存储
  void saveToLocal();

  /// 从本地存储获取
  T? getFromLocal();

  /// 获取响应式数据
  Rx<T?> get value {
    if (_value.value != null) {
      return _value;
    }

    try {
      final valueT = getFromLocal();
      if (valueT != null) {
        _value.value = valueT;
      }
    } catch (e) {
      // 处理获取错误
    }

    return _value;
  }
}

/// 字符串列表偏好数据
class PrefStringListData extends PrefData<List<String>> {
  PrefStringListData(SharedPreferences? sharedPreferences, String key)
      : super(sharedPreferences, key);

  @override
  List<String>? getFromLocal() {
    return sharedPreferences?.getStringList(key);
  }

  @override
  void saveToLocal() {
    sharedPreferences?.setStringList(key, value.value ?? []);
  }
}
